<template>
  <div class="player-profile">
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-else-if="error" class="error">
      <p>{{ error }}</p>
      <button @click="loadPlayer" class="retry-btn">重试</button>
    </div>
    
    <div v-else-if="player" class="profile-content">
      <div class="profile-header">
        <div class="avatar-section">
          <div class="avatar">
            <img 
              v-if="player.avatar" 
              :src="player.avatar" 
              :alt="player.nickname"
              @error="handleAvatarError"
            />
            <div v-else class="avatar-placeholder">
              {{ player.nickname.charAt(0).toUpperCase() }}
            </div>
          </div>
          <div class="basic-info">
            <h1>{{ player.nickname }}</h1>
            <p class="username">@{{ player.username }}</p>
            <div class="status">
              <span :class="['status-indicator', player.status]">
                {{ getStatusText(player.status) }}
              </span>
            </div>
          </div>
        </div>
        
        <div class="action-buttons">
          <button 
            v-if="canAddFriend" 
            @click="handleAddFriend" 
            class="btn btn-primary"
          >
            添加好友
          </button>
          <button 
            v-if="canSendMessage" 
            @click="handleSendMessage" 
            class="btn btn-outline"
          >
            发送消息
          </button>
          <button 
            v-if="isOwnProfile" 
            @click="handleEditProfile" 
            class="btn btn-outline"
          >
            编辑资料
          </button>
        </div>
      </div>
      
      <div class="profile-body">
        <div class="stats-section">
          <h2>统计数据</h2>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-value">{{ player.level }}</div>
              <div class="stat-label">等级</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ player.stats.experience }}</div>
              <div class="stat-label">经验值</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ player.stats.casesSolved }}</div>
              <div class="stat-label">破案数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ formatAccuracy(player.stats.accuracy) }}%</div>
              <div class="stat-label">准确率</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ player.stats.coins }}</div>
              <div class="stat-label">金币</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ player.stats.gems }}</div>
              <div class="stat-label">宝石</div>
            </div>
          </div>
          
          <div class="level-progress">
            <div class="progress-info">
              <span>等级进度</span>
              <span>{{ player.stats.experience }} / {{ getNextLevelExp() }}</span>
            </div>
            <div class="progress-bar">
              <div 
                class="progress-fill" 
                :style="{ width: getLevelProgress() + '%' }"
              ></div>
            </div>
          </div>
        </div>
        
        <div class="achievements-section">
          <h2>成就</h2>
          <div v-if="player.achievements.length > 0" class="achievements-list">
            <div 
              v-for="achievement in player.achievements" 
              :key="achievement.id"
              class="achievement-item"
            >
              <div class="achievement-icon">🏆</div>
              <div class="achievement-info">
                <h4>{{ achievement.name }}</h4>
                <p>{{ achievement.description }}</p>
                <small>{{ formatDate(achievement.achievedAt) }}</small>
              </div>
            </div>
          </div>
          <div v-else class="no-achievements">
            <p>暂无成就</p>
          </div>
        </div>
        
        <div class="preferences-section">
          <h2>偏好设置</h2>
          <div class="preferences-grid">
            <div class="preference-item">
              <span class="preference-label">难度偏好</span>
              <span class="preference-value">{{ getDifficultyText(player.preferences.difficulty) }}</span>
            </div>
            <div class="preference-item">
              <span class="preference-label">案件类型</span>
              <span class="preference-value">{{ getCategoryText(player.preferences.category) }}</span>
            </div>
            <div class="preference-item">
              <span class="preference-label">AI助手</span>
              <span class="preference-value">{{ player.preferences.aiAssistance ? '开启' : '关闭' }}</span>
            </div>
            <div class="preference-item">
              <span class="preference-label">通知</span>
              <span class="preference-value">{{ player.preferences.notifications ? '开启' : '关闭' }}</span>
            </div>
          </div>
        </div>
        
        <div class="activity-section">
          <h2>最近活动</h2>
          <div class="activity-list">
            <div 
              v-for="activity in recentActivities" 
              :key="activity.id"
              class="activity-item"
            >
              <div class="activity-icon">📋</div>
              <div class="activity-info">
                <p>{{ activity.description }}</p>
                <small>{{ formatTimeAgo(activity.timestamp) }}</small>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { usePlayerStore } from '@/stores/player';
import { 
  getPlayerLevelProgress, 
  getNextLevelExperience, 
  getPlayerRoleText, 
  getPlayerStatusText,
  formatAccuracy,
  formatDate,
  formatTimeAgo
} from '@/utils/player';
import { PlayerRole, PlayerStatus, CaseDifficulty, CaseCategory } from '@/entities/Player';
import type { Player } from '@/entities/Player';

const route = useRoute();
const router = useRouter();
const playerStore = usePlayerStore();

// 状态
const loading = ref(true);
const error = ref<string | null>(null);
const player = ref<Player | null>(null);

// 计算属性
const isOwnProfile = computed(() => {
  return playerStore.currentPlayer?.id === route.params.id;
});

const canAddFriend = computed(() => {
  return playerStore.isLoggedIn && 
         !isOwnProfile.value && 
         player.value &&
         !playerStore.currentPlayer?.friends.includes(player.value.id);
});

const canSendMessage = computed(() => {
  return playerStore.isLoggedIn && !isOwnProfile.value;
});

const recentActivities = computed(() => {
  // 模拟最近活动数据
  if (!player.value) return [];
  
  return [
    {
      id: '1',
      description: '完成了案件 #1234',
      timestamp: new Date(Date.now() - 1000 * 60 * 30) // 30分钟前
    },
    {
      id: '2', 
      description: '获得了新成就：破案高手',
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2) // 2小时前
    },
    {
      id: '3',
      description: '等级提升到 ' + player.value.level,
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 24) // 1天前
    }
  ];
});

// 方法
const loadPlayer = async () => {
  try {
    loading.value = true;
    error.value = null;
    
    const playerId = route.params.id as string;
    const foundPlayer = playerStore.getPlayerById(playerId);
    
    if (!foundPlayer) {
      error.value = '玩家不存在';
      return;
    }
    
    player.value = foundPlayer;
  } catch (err) {
    error.value = '加载玩家数据失败';
    console.error('加载玩家失败:', err);
  } finally {
    loading.value = false;
  }
};

const handleAvatarError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.style.display = 'none';
  img.nextElementSibling?.classList.add('show');
};

const handleAddFriend = async () => {
  if (!player.value) return;
  
  try {
    await playerStore.addFriend(player.value.id);
    alert('好友添加成功！');
  } catch (error) {
    alert('添加好友失败：' + (error as Error).message);
  }
};

const handleSendMessage = () => {
  alert('消息功能开发中...');
};

const handleEditProfile = () => {
  router.push('/profile/edit');
};

const getStatusText = (status: PlayerStatus) => {
  return getPlayerStatusText(status);
};

const getRoleText = (role: PlayerRole) => {
  return getPlayerRoleText(role);
};

const getDifficultyText = (difficulty: CaseDifficulty) => {
  const texts = {
    [CaseDifficulty.EASY]: '简单',
    [CaseDifficulty.MEDIUM]: '中等',
    [CaseDifficulty.HARD]: '困难'
  };
  return texts[difficulty];
};

const getCategoryText = (category: CaseCategory) => {
  const texts = {
    [CaseCategory.MURDER]: '谋杀案',
    [CaseCategory.THEFT]: '盗窃案',
    [CaseCategory.MISSING]: '失踪案',
    [CaseCategory.FRAUD]: '诈骗案',
    [CaseCategory.KIDNAPPING]: '绑架案',
    [CaseCategory.CYBER_CRIME]: '网络犯罪'
  };
  return texts[category];
};

const getNextLevelExp = () => {
  if (!player.value) return 0;
  return getNextLevelExperience(player.value.level);
};

const getLevelProgress = () => {
  if (!player.value) return 0;
  return getPlayerLevelProgress(player.value);
};

onMounted(() => {
  loadPlayer();
});
</script>

<style scoped>
.player-profile {
  max-width: 800px;
  margin: 0 auto;
}

.loading,
.error {
  text-align: center;
  padding: 48px 24px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid var(--color-border);
  border-top: 4px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error p {
  color: #dc3545;
  margin-bottom: 16px;
}

.retry-btn {
  padding: 8px 16px;
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.retry-btn:hover {
  background: var(--color-primary-dark);
}

.profile-content {
  background: var(--color-background);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.profile-header {
  background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-primary-dark) 100%);
  color: white;
  padding: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 24px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  background: white;
  border: 4px solid white;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: 700;
  color: var(--color-primary);
  background: var(--color-background-soft);
}

.avatar-placeholder.show {
  display: flex;
}

.basic-info h1 {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 4px 0;
}

.username {
  font-size: 16px;
  opacity: 0.9;
  margin: 0 0 8px 0;
}

.status-indicator {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
}

.status-indicator.online {
  background: #28a745;
}

.status-indicator.offline {
  background: #6c757d;
}

.status-indicator.playing {
  background: #ffc107;
  color: #212529;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 10px 20px;
  border-radius: 6px;
  text-decoration: none;
  font-weight: 600;
  border: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-primary {
  background: white;
  color: var(--color-primary);
}

.btn-outline {
  background: transparent;
  color: white;
  border: 2px solid white;
}

.btn:hover {
  transform: translateY(-2px);
}

.profile-body {
  padding: 32px;
}

.stats-section,
.achievements-section,
.preferences-section,
.activity-section {
  margin-bottom: 48px;
}

.stats-section h2,
.achievements-section h2,
.preferences-section h2,
.activity-section h2 {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 24px 0;
  color: var(--color-text);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: var(--color-background-soft);
  border-radius: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--color-primary);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--color-text-secondary);
}

.level-progress {
  background: var(--color-background-soft);
  padding: 16px;
  border-radius: 8px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: var(--color-text-secondary);
}

.progress-bar {
  height: 8px;
  background: var(--color-background-mute);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: var(--color-primary);
  transition: width 0.3s ease;
}

.achievements-list {
  display: grid;
  gap: 16px;
}

.achievement-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: var(--color-background-soft);
  border-radius: 8px;
}

.achievement-icon {
  font-size: 24px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-primary);
  color: white;
  border-radius: 50%;
}

.achievement-info h4 {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 4px 0;
}

.achievement-info p {
  font-size: 14px;
  color: var(--color-text-secondary);
  margin: 0 0 4px 0;
}

.achievement-info small {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.no-achievements {
  text-align: center;
  padding: 32px;
  color: var(--color-text-secondary);
}

.preferences-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.preference-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: var(--color-background-soft);
  border-radius: 6px;
}

.preference-label {
  font-weight: 500;
  color: var(--color-text);
}

.preference-value {
  color: var(--color-text-secondary);
}

.activity-list {
  display: grid;
  gap: 12px;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: var(--color-background-soft);
  border-radius: 6px;
}

.activity-icon {
  font-size: 16px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-primary);
  color: white;
  border-radius: 50%;
}

.activity-info p {
  margin: 0 0 4px 0;
  font-size: 14px;
}

.activity-info small {
  font-size: 12px;
  color: var(--color-text-secondary);
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 24px;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: center;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>